package com.njtoyo.taxi.admin.service.data.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njtoyo.taxi.admin.handler.common.DateIntervalHandler;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.mapper.secondary.entity.data.DashboardCallDaily;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.data.DashboardCallDailyMapper;
import com.njtoyo.taxi.admin.rest.presenter.data.chart.RankChartItemPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.data.chart.ChartQueryWrapper;
import com.njtoyo.taxi.admin.service.data.CallService;
import com.taxi.entity.common.RestResult;
import com.njtoyo.taxi.entity.backend.AdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@DS(Const.SECONDARY_DS)
public class CallServiceImpl implements CallService {

    @Autowired
    private DashboardCallDailyMapper dashboardCallDailyMapper;

    @Override
    public RestResult chart(AdminUser adminUser, ChartQueryWrapper wrapper) {
        DateIntervalHandler intervalHandler = new DateIntervalHandler(wrapper.getDateGroupType(), wrapper.getInterval(), wrapper.getStartTime(), wrapper.getEndTime());

        List<RankChartItemPresenter> res = intervalHandler.getDateList();
        res.forEach(r -> {
            QueryWrapper<DashboardCallDaily> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("IFNULL(SUM(num), 0)")
                    .eq(Objects.nonNull(wrapper.getCantonId()), "canton_id", wrapper.getCantonId())
                    .isNotNull(Objects.isNull(wrapper.getCantonId()), "canton_id")
                    .between("stats_date", DateUtil.formatDate(r.getStart()), DateUtil.formatDate(r.getEnd()));
            r.setTotal(dashboardCallDailyMapper.selectObjs(queryWrapper).get(0));
        });

        return RestResult.success(res);
    }
}
